<?php

namespace App\Console\Commands;

use App\Episode;
use App\Show;
use Illuminate\Console\Command;
use Symfony\Component\DomCrawler\Crawler;

class SpiderYYETS extends Command
{
    /**
     * The name and signature of the console command.
     *
     * @var string
     */
    protected $signature = 'spider:yyetsep';

    /**
     * The console command description.
     *
     * @var string
     */
    protected $description = '爬取下载资源yyets美剧';

    /**
     * Create a new command instance.
     *
     * @return void
     */
    public function __construct()
    {
        parent::__construct();
    }

    /**
     * Execute the console command.
     *
     * @return mixed
     */
    public function handle()
    {
        //获取登陆cookie
        $header_params = [
            'Host' => 'http://www.zimuzu.tv',
            'Accept'=>'text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,*/*;q=0.8',
            'Accept-Encoding'=>'gzip, deflate, sdch',
            'Accept-Language'=>'en-US,en;q=0.8,zh-CN;q=0.6,zh;q=0.4',
            'Cache-control:'=>'max-age=0',
            'Dnt'=>'1',
            'Referer'=>'https://www.baidu.com/link?url=OOIVn0qbApPkoe99TFbeGI307BTpCTY4pXGJcll69PEQRzlZjqbxMmnq9DoI3AWQ&wd=&eqid=fe299461002fe7600000000557314a9e',
            'Upgrade-Insecure-Requests'=>'1',
            'User-Agent'=>'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_11_3) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/49.0.2623.112 Safari/537.36',
        ];
        //使用共享cookie和伪造headers
        $client = new \GuzzleHttp\Client(['cookies' => true, 'headers' => $header_params]);
        $form_params = [
            'account' => config('app.yyets_user_name'),
            'password' => config('app.yyets_password'),
            'remember' => 1,
            'url_back' => 'http://www.zimuzu.tv/today'];

        $client->request('POST', 'http://www.zimuzu.tv/User/Login/ajaxLogin', ['form_params' => $form_params]);
        //设置登陆cookie 之后 就获取内容
        $res = $client->request('GET', 'http://www.zimuzu.tv/today');
        $html = $res->getBody()->getContents();

        $crawler = new Crawler($html);
        $crawler->filter('tr.list')->each(function(Crawler $row,$i) {
            $area = $row->attr('area');
            $channel = $row->attr('channel');
            $day =$row->attr('day');

            $td1Type = $row->filterXPath('//td[1]')->text();
            $td2Format = $row->filterXPath('//td[2]')->text();
            $td3Name = $row->filterXPath('//td[3]')->text();
            $td5Size = $row->filterXPath('//td[5]')->text();
            //创建db 对象


            $episode = Episode::firstOrNew(['raw_name'=>$td3Name]);
            $episode->size = $td2Format.' '.$td5Size;
            $episode->provider = 'yyets'.' '.$td1Type.' '.$area.' '.$channel.' '.$day;


            $td3Url = $row->filterXPath('//td[3]/a[1]')->attr('href');
            $episode->url_provider = 'http://www.zimuzu.tv' . $td3Url;

            //下载资源
            $row->filterXPath('//td[4]/a')->each(function(Crawler $nodeA,$i) use($episode){

                $value = $nodeA->attr('href');
                if(str_contains($value,'baidu')) {
                    $episode->url_baidupan = $value;
                }
                elseif(str_contains($value,'magnet')) {
                    $episode->url_magnet = $value;
                }
                elseif(str_contains($value,'thunder')) {
                    $episode->url_other = $value;
                }
                elseif(str_contains($value,'ed2k')) {
                    $episode->url_ed2k = $value;
                }else {
                }
            });
            $episode->show_id = 396;
            $episode->name = filterEpisodeRawName($td3Name);

            $episode->save();
            //取区 英文

            $enName = '';
            if (preg_match('/(\w+\.)+(?=\d{3}\.|s\d+e\d+\.|Ep\d+\.|e\d+\.)/i',$td3Name, $matches)) {
                $enName = $matches[0];
                $enName = str_ireplace('.',' ',$enName);
                $enName = trim($enName);
                // var_dump($enName);
            }
            $name_zh='';
            if (preg_match('/[\x{4e00}-\x{9fa5}]+\W{0,2}[\x{4e00}-\x{9fa5}]+\W*\./u',$td3Name, $matches)) {
                //var_dump($matches);
                $name_zh = $matches[0];
                $name_zh = str_ireplace('.',' ',$name_zh);
                $name_zh = trim($name_zh);
            }
            $enName = str_ireplace('(','',$enName);
            $enName = str_ireplace(')','',$enName);
            //$show = Show::firstOrCreate(['name_en'=>$enName]);
            $show = Show::where('name_en','like',$enName.'%')->first();
            if ($show && $show->id != 1) {
                $show->name_zh = $name_zh;
                $show->updated_at = $episode->created_at;
                $show->save();
                $episode->show_id = $show->id;
            } else {
                if($episode->show_id<1) {
                    $episode->show_id = 396;
                }
            }
            $episode->save();
        });

        unset($html,$client,$crawler);
    }
}
